package cn.lystudio.rohm_time_op.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.lystudio.rohm_time_op.entity.dto.DailyConfirmDTO;
import cn.lystudio.rohm_time_op.entity.po.DailyConfirmPO;
import cn.lystudio.rohm_time_op.entity.po.UsersPO;
import cn.lystudio.rohm_time_op.mapper.DailyConfirmPOMapper;
import cn.lystudio.rohm_time_op.mapper.UsersPOMapper;
import cn.lystudio.rohm_time_op.service.DailyConfirmService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
@Slf4j
public class DailyConfirmServiceImpl implements DailyConfirmService {
    @Resource
    private DailyConfirmPOMapper dailyConfirmPOMapper;

    @Resource
    private UsersPOMapper usersPOMapper;

    @Override
    public Integer addDailyConfirm(DailyConfirmPO dailyConfirmPO) {
        int res=-1;
        LambdaQueryWrapper<DailyConfirmPO> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(DailyConfirmPO::getMachineNo,dailyConfirmPO.getMachineNo())
                .eq(DailyConfirmPO::getRecordTimeDT, dailyConfirmPO.getRecordTimeDT());
        if(CollUtil.isNotEmpty(dailyConfirmPOMapper.selectList(wrapper))){
            res = dailyConfirmPOMapper.update(dailyConfirmPO,wrapper);
        }else {
            res= dailyConfirmPOMapper.insert(dailyConfirmPO);
        }
        return res;
    }

    @Override
    public DailyConfirmDTO getDailyConfirm(DailyConfirmPO dailyConfirmPO) {
        // 1.获取数据
        LambdaQueryWrapper<DailyConfirmPO> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(DailyConfirmPO::getMachineNo, dailyConfirmPO.getMachineNo())
                .eq(DailyConfirmPO::getRecordTimeDT, dailyConfirmPO.getRecordTimeDT())
                .last("LIMIT 1");
        DailyConfirmPO dailyConfirmPO1 = dailyConfirmPOMapper.selectOne(wrapper);
        if(ObjectUtil.isEmpty(dailyConfirmPO1)) return null;
        // 2.获取所有用户
        List<UsersPO> userAll = usersPOMapper.selectList(null);
        // 3.封装数据
        DailyConfirmDTO dailyConfirmDTO =new DailyConfirmDTO();
        dailyConfirmDTO.setDailyConfirm(dailyConfirmPO1);
        dailyConfirmDTO.setUser(
                CollUtil.findOne(userAll,user->user.getUserCode().equals(dailyConfirmPO1.getUserCode()))
        );

        return dailyConfirmDTO;
    }
}
